<?php
namespace News\Controller;
use Think\Controller;
//首页控制器 IndexController.class.php
class IndexController extends CommonController{
    public function __construct() {
        parent::__construct();
        //打开企业通讯录选人
        $this -> openEnterpriseContact($this->jssdk);
        $this -> assign('coprid',$this -> corpid);
        $this -> assign('signPackage',$this -> signPackage);
    }
    
    public function index(){
        $data = I('get.');
        //获取成员userid
        $userid_name = $this -> corpid . '_userid';
        $this -> userid_name = $userid_name;

        /** 调试代码开始 */
        //$userid = "981fd5fa16";
        /** 调试代码结束 */

        if(!$userid=session($userid_name)){
            $userid = $this -> getUserid($data);
        }

        //获取成员所在部门id
        foreach($this -> all_corp_user as $k => $v){
          if($v['userid']==$userid){
            //获取部门信息
            $user_department = $v['department'];
          }
        }

        $this -> assign('userid',$userid);
        $this -> assign('department',$user_department);
        $this -> display();
    }
    
    /**
    * 企业号通讯录选择人
    */
    private function openEnterpriseContact($jssdk){
        //获取token
        $token = $this -> token;
        //获取管理组凭证
        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={$token}&type=contact";
        $res = $this -> https_curl($url);
        $res = json_decode($res,true);
        $group_id = $res['group_id'];
        $ticket = $res['ticket'];
        //生成通讯录签名
        $noncestr = $this -> createNonceStr();
        $timestamp = time();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $string = "group_ticket={$ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
        $signature = sha1($string);
        $this -> assign([
            'groupId' => $group_id,
            'timestamp' => $timestamp,
            'nonceStr' => $noncestr,
            'signature' => $signature,
        ]);
    }
    
    /**
    * 生成随机字符串
    */
    private function createNonceStr($length = 16) {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $str = "";
      for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
    }
    
    /**
     * 通过code获取成员userid
     * @param type $data
     * @return type
     */
    public function getUserid($data){
       $code = $data['code'];
       if(!$code){
           $this -> error('未经授权用户e1!');
           exit;
       }
       $access_token = $this -> token;
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$access_token}&code={$code}";
       $res = json_decode($this -> https_curl($url),true);
       if(!$userid = $res['UserId']){
           $this -> error('未经授权用户e2!');
       }
       session($this -> userid_name,$userid);
       return $userid;
   }
   
    /**
    * 发送消息
    */
    public function sendMessage(){
        //整理数据
        $data = I('post.');
        //发起方成员userid
        $userid = $data['userid'];
        //消息标题
        $title = $data['title'];
        //消息正文
        $content = $data['content'];
        //发送成员集合
        $user_list = $data['person_list'];
        //发送部门集合
        $dep_list = $data['dep_list'];

        $dep_all_user_list = array();
        //获取所有部门成员集合
        if(!empty($dep_list)){
            $dep_set = explode(',',$dep_list);
            array_pop($dep_set);
            foreach($dep_set as $id){
              $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={$this -> token}&department_id={$id}&fetch_child=1&status=1";
              $res = json_decode($this -> https_curl($url),true)['userlist'];
              $id_list = array_column($res,'userid');
              $dep_all_user_list = array_merge($id_list);
            }
        }
        //检测是否为全选操作
        $person_type = $data['person_type'];
        //分析是否为全部成员
        if($person_type==1){
            $temp = explode(',',$user_list);
            $user_list = array_merge($temp,$dep_all_user_list);
            $db_user_list = implode(',',$user_list);
            $user_list = implode('|',$user_list);
        }elseif($person_type==2){
            //全选成员
            $db_user_list = 'all';
            $user_list = '@all';
        }
        $token = $this -> token;
        //存储消息到数据库
        $news_id = $this -> saveMesToDB($title,$content,$userid,$db_user_list);

        //生成跳转点击跳转url
        $jump_url = $this -> createUrl($news_id);
        $content = mb_substr($content,0,30) . '...';
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$token";
        $json = '{
                  "touser": "'.$user_list.'",
                  "msgtype": "news",
                  "agentid": '.$this->agentid.',
                  "news": {
                      "articles":[
                          {
                              "title": "【新消息】'.$title.'",
                              "description":"消息简要:'.$content.'",
                              "url": "'.$jump_url.'",
                              "picurl": ""
                          }    
                      ]
                  }
               }';

        //发送请求
        $temp = $this ->https_curl($url, $json);
        $res = json_decode($temp,true);
        //dump($res);exit;
        //检测消息发送是否成功
        if($res['errorcode']==0){
            $this -> success('发送成功!');

        }else{
            $this -> error('发送失败!');
        }
    }
    
    /**
    * 生成跳转url
    */
    private function createUrl($news_id){
       $r_url = C('APP_URL');
       $newagentid = C('NEWS_AGENID');
       $REDIRECT_URI = urlencode($r_url.'index.php?m=News&c=Message&a=showContent');
       $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->corpid}&redirect_uri={$REDIRECT_URI}&response_type=code&scope=snsapi_base&agentid={$newagentid}&state={$this->corpid}-{$news_id}#wechat_redirect";
       //$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->corpid}&redirect_uri={$REDIRECT_URI}&response_type=code&scope=snsapi_base&state={$this->corpid}-{$news_id}#wechat_redirect";
       return $url;
    }
    
    /**
    *存储消息到数据库
    */
    private function saveMesToDB($title,$content,$userid,$db_user_list){
         $GLOBALS['redis'] -> select(1);
         $id = $userid.'_'.time();
         $temp['title'] = $title;
         $temp['content'] = $content;
         $temp['sendto'] = $db_user_list;
         $msg_db_name = $this -> corpid . '_all_messages';
         $GLOBALS['redis'] -> hset($msg_db_name,$id,serialize($temp));
         //返回唯一码
         return $id;
     }
     
    /**
     * ajax获取通讯录选中成员数据
     */
    public function getUserListInfo(){
        //从缓存中获取所有企业号下所有成员以及部门成员数据 头像+姓名+userid
        $all_user = $this -> corpid . '_all_user';
        $cache =  new CacheController($this->corpid);
        $GLOBALS['redis'] -> select(1);
        if(!$all_user_list= unserialize($GLOBALS['redis']->get($all_user))){
            $all_user_list = $cache -> cacheAllUser();
        }
        $all_department_user = $this -> corpid . '_all_department_user';
        if(!$all_dep_user_list= 
                unserialize($GLOBALS['redis']->get($all_department_user))){
            $all_dep_user_list = $cache -> cacheDepartment();
        }
        //userid name avatar
        $data = I('post.');
        //获取标记 state 1 部门成员 2 所有成员
        $state = $data['state'];
        $user_list = $data['user_list'];
        $dep_list = $data['department_list'];
        if($state==1){
        //选中部门及成员情况
            //1.获取单选成员集合
            $p_buffer = [];
            $index = 0;
            //获取成员信息
            $user_list = explode(',',$user_list);
            array_pop($user_list);
            foreach($user_list as $k => $v){
                foreach($all_user_list as $k2 => $v2){
                    if($v2['userid']==$v){
                        $p_buffer[$index]['name'] = $v2['name'];
                        $p_buffer[$index]['userid'] = $v2['userid'];
                        $p_buffer[$index]['avatar'] = $v2['avatar'];
                        $index++;
                    }
                }
            }
            //2.获取部门成员集合
            $dep_list = explode(',',$dep_list);
            array_pop($dep_list);
            foreach($dep_list as $k => $v){
               if($temp = $all_dep_user_list[$v]){
                   //分析成员重复添加
                   foreach($temp as $k2 => $v2){
                       if(!in_array($v2['userid'],$user_list)){
                           $p_buffer[$index]['name'] = $v2['name'];
                           $p_buffer[$index]['userid'] = $v2['userid'];
                           $p_buffer[$index]['avatar'] = $v2['avatar'];
                           $index++;
                       }
                   }
               }
            }
            $this ->ajaxReturn($p_buffer);
        }
    }
}